package homework3;

import java.io.*;

public class CopyData {

    public boolean copy(String originFile, String copyFile) {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;

        try {
            // 1.创建BufferedReader类型的对象与originFile文件关联
            bufferedReader = new BufferedReader(new FileReader(originFile));
            // 2.创建BufferedWriter类型的对象与copyFile文件关联
            bufferedWriter = new BufferedWriter(new FileWriter(copyFile));
            // 3.不断地从输入流中读取一行字符串并写入到输出流中
            System.out.println("正在拷贝文件" + originFile + " 到" + copyFile + "中");
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4.关闭流对象并释放有关的资源
            if (null != bufferedWriter) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != bufferedReader) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public void file_ergodic(File originDirectory) {
        //遍历源文件

        if (originDirectory.isFile()) {  //是文件直接拷贝
            System.out.println(originDirectory.getAbsolutePath());
            String copyPath = originDirectory.getAbsolutePath().replace("origin_data", "copy_data");
//            File file = new File(copyPath);
//            try {
//                boolean newFile = file.createNewFile();
//                System.out.println(newFile ? "文件创建成功" : "文件创建失败");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
            boolean copy = copy(originDirectory.getAbsolutePath(), copyPath);
            System.out.println(copy ? "拷贝成功！" : "拷贝失败");
        } else if (originDirectory.isDirectory()) { // 是目录继续找子文件
            //创建目录
            String copyDirectory = originDirectory.getAbsolutePath().replace("origin_data", "copy_data");
            File file = new File(copyDirectory);
            boolean mkdir1 = file.mkdir();
            System.out.println(mkdir1 ? "文件夹创建成功" : "文件夹创建失败");

            File[] files = originDirectory.listFiles();
            for (File file1 : files) {
                file_ergodic(file1);   //递归遍历目录下的文件及文件夹
            }
//            if (0 == files.length) {
//
//            } else {
//                for (File file1 : files) {
//                    file_ergodic(file1);   //递归遍历目录下的文件及文件夹
//                }
//            }
        } else {
            System.out.println("------------------");
        }
    }
}
